package com.minshenglife.zanzan.web.weixin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.minshenglife.commons.security.utils.AccessTokenUtils;
import com.minshenglife.commons.security.utils.pp.UserIdentify;
import com.minshenglife.commons.security.utils.pp.UserIdentify.UserType;
import com.minshenglife.zanzan.entity.EMOUserGroup;
import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.pub.message.custservice.GetAccessTokenMessage;
import com.minshenglife.zanzan.pub.utils.SignUtil;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.service.AccessTokenService;
import com.minshenglife.zanzan.service.EMOUserGroupService;
import com.minshenglife.zanzan.service.EMOUserService;
import com.minshenglife.zanzan.service.UserService;
import com.minshenglife.zanzan.web.weixin.form.CoreForm;
import com.minshenglife.zanzan.web.weixin.service.EMOCoreService;
import com.minshenglife.zanzan.web.weixin.service.EMOWXBaseServcie;
import com.minshenglife.zanzan.web.weixin.service.WXBaseService;
import com.nationsky.pub.utils.StringUtils;

/**
 * 
 * @author jianghaibo
 *
 */
@Controller
@RequestMapping("/emocore")
public class EMOCoreController extends BaseController {

	Logger log = LoggerFactory.getLogger(EMOCoreController.class);

	@Resource
	EMOCoreService emoCoreService;
	@Resource
	EMOUserGroupService emoUserGroupService;
	@Resource
	AccessTokenService accessTokenService;

	@RequestMapping("/main.do")
	@ResponseBody
	public void main(HttpServletRequest request, HttpServletResponse response) {
		log.info("===========log start===main");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		try {
			PrintWriter out;
			out = response.getWriter();
			if (echostr == null || "".equals(echostr)) {
				//
				String respMessage = emoCoreService.processRequest(request);
				System.out.println("---------main------end" + respMessage);
				respMessage = com.minshenglife.zanzan.pub.utils.StringUtils
						.replaceBlank(respMessage);
				System.out.println("---------replaceBlank------end"
						+ respMessage);
				out.print(respMessage);
			} else {
				String timestamp = request.getParameter("timestamp");
				String nonce = request.getParameter("nonce");
				String signature = StringUtils.processStrings(request
						.getParameter("signature"));
				// 校验signature，成功后返回echostr
				// if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				out.print(echostr);
				// }
			}
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		log.info("===========log end===main");
	}

	@RequestMapping("/toPageDoor.do")
	public void toPageDoor(HttpServletRequest request,
			HttpServletResponse response, CoreForm coreForm) {
		log.info("===========log start===topagedoor");
		String action = "/emocore/toPageDoor.do";
		String redirectUrl = WXKeys.WX_BASEURL + action;
		log.debug(request.getRequestURI());
		try {
			// 用户同意授权，获取code
			if (!StringUtils.isNullOrEmpty(coreForm.getKey())) {
				log.debug("用户同意授权，获取code");
				String url = EMOWXBaseServcie.getCodeByAuthorizeUrl(
						redirectUrl, false, null, coreForm.getKey());
				log.debug(url);
				response.sendRedirect(url);
			}
			// 通过code换取网页授权access_token
			else if (!StringUtils.isNullOrEmpty(coreForm.getState())
					&& !StringUtils.isNullOrEmpty(coreForm.getCode())) {
				log.debug("通过code换取网页授权access_token");
				GetAccessTokenMessage msg = EMOWXBaseServcie
						.getAccessTokenByCode(coreForm.getCode());
				log.debug("access_token为--->" + msg.getAccess_token());
				if (msg != null) {
					String openId = msg.getOpenid();
					if (!StringUtils.isNullOrEmpty(openId)) {
						String topage = toWebPage(coreForm.getState(), openId,
								response);
						log.debug(topage);
						response.sendRedirect(topage);
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		log.info("===========log end===topagedoor");
	}

	/**
	 * 处理菜单事件
	 * 
	 * @param key
	 *            事件key值
	 * @param access_token
	 *            事件请求者的微信号access_token
	 * @param baseUrl
	 * @return
	 */
	private String toWebPage(String key, String userOpenId,HttpServletResponse response) {
		// 校验请求者是否已经绑定员工号
		EMOUserGroup usergroup = emoUserGroupService.getUserByOpenid(userOpenId);
		String access_token = null;
		if (usergroup != null) {
			access_token = AccessTokenUtils.newToken(new UserIdentify(UserType.weixin, userOpenId), usergroup.getOpenid());
			accessTokenService.insertAccessToken(usergroup, access_token);// 插入页面时效
		}
		String toPage = "";
		if (usergroup == null) {
			// 用时间串生成access_token
			access_token = AccessTokenUtils.newToken(new UserIdentify(UserType.weixin, userOpenId), String.valueOf(new Date().getTime()));
			accessTokenService.insertAccessTokenOfNotUser(userOpenId,access_token);// 插入页面时效
			toPage = WXKeys.WX_BASEURL + "/jsp/weixin/emo/register.jsp?access_token=" + access_token;
		} else if (WXKeys.WX_EMO_BTN_MENU_HOT.equals(key)) {
//			toPage = WXKeys.WX_BASEURL + "/jsp/weixin/redFlowerRank.jsp?access_token=" + access_token;
			toPage = "http://www.minshenglife.com";
		} else if (WXKeys.WX_EMO_BTN_MENU_WONDERFUL.equals(key)) {
//			toPage = WXKeys.WX_BASEURL + "/jsp/weixin/redFlowerRank.jsp?access_token=" + access_token;
			toPage = "http://www.minshenglife.com/templet/default/About_colorful.jsp?id=1005";
		} else {
			// 请求错误页面
		}
		return toPage;
	}

	public static void main(String[] args) {
		String access_token = AccessTokenUtils.newToken(new UserIdentify(
				UserType.weixin, "oksggtz9vqsnsNdkwp5wD4Vag6YA"),
				"oksggtz9vqsnsNdkwp5wD4Vag6YA");
		String access_token1 = AccessTokenUtils.newToken(new UserIdentify(
				UserType.weixin, "oksggtz9vqsnsNdkwp5wD4Vag6YA"),
				"oksggtz9vqsnsNdkwp5wD4Vag6YA");
		System.out.println(access_token.equals(access_token1));
	}
}
